package com.cmpanyandi.elearning.wordsdriller.activity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;

import com.cmpanyandi.elearning.utils.db.DbAdapter;
import com.cmpanyandi.elearning.wordsdriller.model.Dictionary;
import com.cmpanyandi.elearning.wordsdriller.model.DictionaryItem;

/**
 * This activity is responsible for displaying list of dictionary items.
 * 
 * @author wojtek
 * 
 */
public class DictionaryItemSearch extends DictionaryActivityForm {

    private Long dictionaryId;
    private AutoCompleteTextView searchView;
    private ImageView displayItem;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	setContentView(R.layout.dictionary_item_search);
	super.onCreate(savedInstanceState);
	
	searchView = (AutoCompleteTextView) findViewById(R.id.searchitem);
	dictionaryId = getIntent().getExtras().getLong(DictionaryItem.DICTIONARY);
	ItemListAdapter adapter = new ItemListAdapter(this, getCursorResult(), dictionaryId);
	searchView.setAdapter(adapter);
	mainDescription.setText(R.string.dictionary_item_search + getDictionaryName());
	displayItem.setOnClickListener(new View.OnClickListener() {
	    @Override
	    public void onClick(View v) {
		Intent i = new Intent(searchView.getContext(), DictionaryItemEdit.class);
		DictionaryItem item = getItemByName(searchView.getText().toString());
		populateIntentFromDictionaryItem(i, item);
		startActivity(i);
		
	    }
	});
	
	
	
	
    }
    
    private void populateIntentFromDictionaryItem(Intent i, DictionaryItem item) {
	i.putExtra(DictionaryItem.PK, item.getPk());
	i.putExtra(DictionaryItem.NAME, item.getName());
	i.putExtra(DictionaryItem.DESCRIPTION, item.getDescription());
	i.putExtra(DictionaryItem.CONTEXT, item.getContext());
	i.putExtra(DictionaryItem.DICTIONARY, item.getDictionary().getPk());
    }
   
    
    private DictionaryItem getItemByName(String name) {
	DictionaryItem item = new DictionaryItem();
	item.setDictionary(new Dictionary(dictionaryId));
	item.setName(name);
	Cursor cursor = DbAdapter.getInstance().fetchBeans(item);
	if (cursor != null) {
	    cursor.moveToFirst();
	}
	item.initFromCursor(cursor);
	return item;
	
    }
    
    private String getDictionaryName() {
	Dictionary dict = new Dictionary(dictionaryId);
	dict = (Dictionary)DbAdapter.getInstance().getByPK(dict);
	return dict.getName();
    }
    private Cursor getCursorResult() {
	DictionaryItem item = new DictionaryItem();
	item.setDictionary(new Dictionary(dictionaryId));
	return DbAdapter.getInstance().fetchBeans(item);
    }

    @Override
    protected String getStateProperty() {
	// TODO Auto-generated method stub
	return null;
    }

}
